package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.RoleDto;
import com.itheima.ydd.entity.Role;
import com.itheima.ydd.mapper.RoleMapper;
import com.itheima.ydd.service.MenuService;
import com.itheima.ydd.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色管理
 */
@Slf4j
@RestController
@RequestMapping("sys_role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @GetMapping("allData")
    public ResultData all(){
        List<Role> list = roleService.list();
        return ResultData.ok("查询成功",list);
    }
    /**
     * 分页查询,角色展示
     * @param name
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("list")
    public ResultData list(String name, int page, int limit){
        Page<Role> rolePage = new Page<>(page,limit);
        LambdaQueryWrapper<Role> lqw = new LambdaQueryWrapper<>();
        lqw.like(name != null,Role::getName,name);
        roleService.page(rolePage,lqw);

        return ResultData.ok("",PageResult.getPage(rolePage));
    }

    /**
     * 通过id回显需要修改的角色权限数据
     * @param id
     * @return
     */
    @GetMapping("rowInfo")
    public ResultData rowInfo(String id){
        RoleDto roleDto = roleService.getRole(id);
        return ResultData.ok("返回要修改数据",roleDto);
    }

    /**
     * 修改角色权限数据
     * @param roleDto
     * @return
     */
    @PostMapping("update")
    public ResultData update(@RequestBody RoleDto roleDto){
        List<String> menuids = roleDto.getMenuids();
        String id = roleDto.getId();
        roleService.updateMenu(menuids,id);
        return ResultData.ok("角色修改成功","");
    }

    /**
     * 添加角色
     * @param roleDto
     * @return
     */
    @PostMapping("add")
    public ResultData add(@RequestBody RoleDto roleDto){
        roleService.saveWithMenu(roleDto);
        return ResultData.ok("角色添加成功","");
    }

    /**
     * 删除角色
     * @param id
     * @return
     */
    @GetMapping("del")
    public ResultData del(String id){
        roleService.del(id);
        return ResultData.ok("删除角色成功","");
    }
}
